/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {
	// Old sorting constants
	const SORT_ASCENDING			= 1;
	const SORT_DESCENDING			= 2;
	
	
	var highlightNode = null;
	var highlightColor = "yellow";
	var highlightBorder = "black";
	var AE = AccessibilityExtension.ns;  
	AE.highlightedNodes = new Array();
	
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
	{
	accessext_getActiveValue: function (tbx) {
		try {
		if (tbx && typeof(tbx.childNodes) != 'undefined') {
			var treeChildren = tbx.getElementsByTagName("treechildren");
			if (treeChildren.length == 1) {
				if (treeChildren[0].childNodes.length >= 0 &&
						tbx.currentIndex < treeChildren[0].childNodes.length && tbx.currentIndex >= 0) {
					return treeChildren[0].childNodes[tbx.currentIndex].getAttribute("value");
				}
			}
		}
		} catch (e) {}
		return -1;
	},
	
	accessext_toggleSortColumn: function (column) {
		if (column == AE.sortColumn)
			AE.sortDirectionAscending = !AE.sortDirectionAscending;
		else {
			AE.sortDirectionAscending = true;
			AE.sortColumn = column;
		}
		AE.sortDirection=AE.sortDirectionAscending;
		UpdateTreeView();
	},
	
	accessext_toggleSortColumn_main: function (column) {
		if (column == AE.sortColumn_main)
			AE.sortDirectionAscending_main = !AE.sortDirectionAscending_main;
		else {
			AE.sortDirectionAscending_main = true;
			AE.sortColumn_main = column;
		}
		AE.sortDirection=AE.sortDirectionAscending_main; //sortDirection is used by updateTreeView()
		UpdateTreeViewMain();
	},
	
	accessext_sortColumnElements: function (a,b) {
		if (a[AE.sortProperty] == b[AE.sortProperty]) {
			return 0;
		}
		if (AE.sortDirection) {
			if (a[AE.sortProperty] > b[AE.sortProperty]) {
				return 1;
			}
		} else if (a[AE.sortProperty] < b[AE.sortProperty]) {
			return 1;
		}
		return -1;
	},
	
	accessext_listSearchOnKeyPress: function (e) {
		var letter = String.fromCharCode(e.charCode).toLowerCase();
		var index = listbox.selectedIndex;
		var i;
		if(letter < 'a' || letter > 'z' || e.altKey || e.metaKey || e.ctrlKey) {
			return;
		}
			
		for(i = index + 1; i < AE.dataarray.length; i ++) {
			if(AE.dataarray[i].text.charAt(0).toLowerCase() == letter) {
				listbox.selectedIndex = i;
				listbox.scrollToIndex(i);
				return;
			}
		}
		for(i = 0; i < index; i ++) {
			if(AE.dataarray[i].text.charAt(0).toLowerCase() == letter) {
				listbox.selectedIndex = i;
				listbox.scrollToIndex(i);
				return;
			}
		}
	},
	
	createXULElement: function (tagName) {
		return (document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",tagName));
	},
	
	
	/****** TODO : Lots of redundancy left over from early versions *******/
	
	accessext_focusOnNode: function (node,index) {
		accessext_scrollToNodeCentered(node);
		var alt_label = document.getElementById("label-alt-text");
		if(node && AE.mydoc && alt_label ) {
			alt_label.value = "";
			if (AE.dataarray[index].alt) {
				alt_label.value = AE.dataarray[index].alt;
			}
		}
	},
	
	accessext_highlightNode: function (node) {
		accessext_clearHighlightedNodes();
		highlightNode = accessext_CreateHighlightNode();
		accessext_AttachHighlightNode(node); //detaches from existing parent it necessary
		accessext_PositionHighlightNode(node);
	},
	
	/**
	 * Remove the accessext-highlight-div highlight node.
	 * Note:  highlightNode.parentNode.removeChild(highlightNode); may  N O T be used by itself alone since each dialog has no idea that 
	 * another dialog may be open and using highlighting.
	 * @return nothing.
	 * @author Sandy Foltz
	*/
	
	accessext_clearHighlightedNodes: function () {
		if (AE.mydoc.defaultView) { //only exists if the browser window is still open
			var accessextNode = AE.mydoc.defaultView.document.getElementById("accessext-highlight-div");
			if (accessextNode != null) {
				if (accessextNode.parentNode != null){
					accessextNode.parentNode.removeChild(accessextNode);	
				}
			} else { 
				if (highlightNode != null) {
					if (highlightNode.parentNode != null) {
						highlightNode.parentNode.removeChild(highlightNode);
					}
				}
			}
			for(i = 0; i < 4; i ++) {
				accessextNode = AE.mydoc.defaultView.document.getElementById("accessext-highlight-div-tablehelp-" + i);
				if (accessextNode != null) {
					if (accessextNode.parentNode != null){
						accessextNode.parentNode.removeChild(accessextNode);	
					}
				}
			}
		}
		highlightNode = null;
		return;
	},
	
	accessext_scrollAndHighlightNode: function (node) {
		accessext_scrollToNode(node);
		var disableHighlightingNode = document.getElementById('checkbox-disable-highlighting')
		if (disableHighlightingNode){
			if (disableHighlightingNode.getAttribute("checked") == 'true') {		
				return;
			}
		}	
		accessext_highlightNode(node);
	},
	
	accessext_treeboxScrollAndHighlightNode: function () {
		var treeChildren = AE.treebox.getElementsByTagName("treechildren");
		if(this.inDelete == true) return;
		
		var node;
		
		accessext_clearHighlightedNodes();
		var index = AE.treebox.currentIndex;
		if(index < 0 || index >= AE.dataarray.length || index == null) {
			node = null;
		} else {
			//This snippet is needed for the list of links, since value!=index if duplicates removed
			var value = treeChildren[0].childNodes[index].getAttribute("value");
			node = AE.dataarray[value].node;
			index = value;
		}
		if (node == null) {
			return;
		}
		if (node.nodeName == 'FRAME' || node.nodeName == 'IFRAME') {
			node = node.contentDocument.body;
		}
		
		if (node == null)
			return;
		
		accessext_scrollToNodeCentered(highlightNode);
		accessext_highlightNode(node);
		accessext_focusOnNode(highlightNode,index);
	},
	
	accessext_open_longDesc: function () {
		try {
			//still getting called even when button is disabled, Why?
			var longdescbutton  = document.getElementById("button-longdesc");
			if (longdescbutton.disabled == true) return;
		
			var index = AE.treebox.currentIndex;
			if (index < 0) {
				return false;
			}
			var node = AE.dataarray[index].node;
			//Fetch the URL of the calling window
			var longdesc = accessext_makeURLAbsolute(node.ownerDocument.location,AE.dataarray[index].longdesc);
			accessext_generatePage(longdesc);
			return true;
		} catch (ex) {
			accessext_consoleDump('accessext_open_longDesc exception: ', ex);
		}
	},
	
	accessext_GlobalCleanup: function () {
		accessext_clearHighlightedNodes();
		return true;
	},
	
	createXULElement: function (tagName) {
		return (document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",tagName));
	},
	
	accessext_clearTreeItems: function (tbx) {
		try {
			var treeChildren = tbx.getElementsByTagName("treechildren");
			if (treeChildren.length !=1) {
				//SF 2/12/08 in FF3 beta 2, the following is the statement at somehow disables the xul:splitter (the grippy/arrows are missing)
				//creating zul on the fly doe not have the problem of disabling the splitters.
				//treeChildren = document.createElement("treechildren");
				treeChildren = createXULElement("treechildren");
				tbx.appendChild(treeChildren);
				treeChildren = tbx.getElementsByTagName("treechildren");
			}
		
			treeChildren = treeChildren[0];
		
			this.inDelete = true; //tell accessext_treeboxScrollAndHighlightNode() to skip it we are just deleting not selecting
			while(treeChildren.hasChildNodes()) {
				treeChildren.removeChild(treeChildren.firstChild);
			}
			this.inDelete = false;
		
			return treeChildren;
		} catch (ex) {
			accessext_consoleDump('accessext_clearTreeItems exception: ', ex);
		}
	},
	
	UpdateTreeView_common: function (theTreebox,defaultSortProperty,theSortColumn,columnMappings,theDataArray) {
		var treeItem;
		
		//Clear the children and create a new one
		var treeChildren = accessext_clearTreeItems(theTreebox);
		
		//Sort
		//First clear all directions
		var cols = theTreebox.getElementsByTagName("treecols");
		if (cols.length == 1) {
			for (var i = 0; i < cols[0].childNodes.length; i ++) {
				cols[0].childNodes[i].setAttribute("sortDirection","");
			}
		}
		
		var sc = document.getElementById(theSortColumn);
		sc.setAttribute("sortDirection", AE.sortDirectionAscending ? "ascending" : "descending");
		AE.sortProperty = defaultSortProperty;
		if (columnMappings[theSortColumn]) {
			AE.sortProperty = columnMappings[theSortColumn];
		}
		else {
			if (theSortColumn.indexOf('list-header-') == 0) {
				//SMF assumes the xul ids use the same data element name from the object prefixed with 'list-header-'
				// in otherwords list-header-order is filled with the 'order' data element
				// list-header-type is filled with the 'type' data element
				AE.sortProperty = theSortColumn.substring(12);
			}
		}
		
		
		theDataArray.sort(accessext_sortColumnElements);
		
		//Finally add elements to the list
		for(i = 0; i < theDataArray.length; i ++) {
			//Hide duplicates
			if (theDataArray[i].display == true) {
				treeItem = theDataArray[i].getTreeNode(document);
				treeItem.setAttribute("value", i);
				treeChildren.appendChild(treeItem);
			}
		}
	},
	
	accessext_toggleShowColumn: function (id) {
		var element = this.document.getElementById(id);
		if (element && element.id == id && element.localName.toLowerCase() == 'treecol') {
			element.hidden = !element.hidden;
		}
	},
	
	accessext_setShowColumn: function (id,show) {
		var element = this.document.getElementById(id);
		if (element && element.id == id && element.localName.toLowerCase() == 'treecol') {
			element.hidden = !show;
		}
	},
	
	accessext_searchOnKeyPress_common: function (event,tbx,data) {
		if (event.altKey || event.metaKey || event.ctrlKey) {
			return false;
		}
		var letter = String.fromCharCode(event.charCode).toLowerCase();
		var index = tbx.currentIndex;
		var i;
			
		for(i = index + 1; i < data.length; i ++) {
			if(data[i].getMainColumnText().charAt(0).toLowerCase() == letter) {
				scrollTreeboxToRow(tbx,i);
				return true;
			}
		}
		for(i = 0; i < index; i ++) {
			if(data[i].getMainColumnText().charAt(0).toLowerCase() == letter) {
				scrollTreeboxToRow(tbx,i);
				return true;
			}
		}
		return false;
	}
});
}});
